<?php

function gain_string_cut($string){
	if (strlen($string) > 150) $string = substr($string,0,150).'...';
	return $string;
}

function dataSize($bytes,$type=''){
	$giga = pow(2,30);
	$mega = pow(2,20);
	$kilo = pow(2,10);
	if ($bytes == 0) return '0';
	if ($type == 'giga') {
		if (round($bytes/$giga,2) != 0) return number_format(($bytes/$giga),2).' G';
		else return '0';
	}
	if ($type == 'mega') {
		if (round($bytes/$mega,2) != 0) return number_format(($bytes/$mega),2).' M';
		else return '0';
	}
	if ($type == 'kilo') {
		if (round($bytes/$kilo,2) != 0) return number_format(($bytes/$kilo),2).' K';
		else return '0';
	}
	if ($type == 'byte') {
		if (round($bytes/$bytes,2) != 0) return number_format(($bytes/$bytes),2).' B';
		else return '0';
	}
	if ($bytes >= $giga) return number_format(($bytes/$giga)).' G';
	if ($bytes >= $mega) return number_format(($bytes/$mega)).' M';
	if ($bytes >= $kilo) return number_format(($bytes/$kilo)).' K';
	return number_format($bytes).' B';
}

function debug_format_print_r($r,$print_r = true){
	if ($print_r) {
		$r = print_r($r, true);
		$r = str_replace("\n", '<br/>', $r);
	} else {
		$r = str_replace('\n', '<br/>', $r);
	}
	$r = str_replace(" ", '&nbsp;', $r);
	return $r;
}

if ($_REQUEST['ajax'] == 1) {
	define('PATH', dirname(__FILE__).'/../../');
	require_once(PATH.'config.php');
	require_once(PATH.'/lib/fw/session.php');

	if ($_REQUEST['position'] != '') {
		$_SESSION[$_REQUEST['div']]['top']= $_REQUEST['top'] ;
		$_SESSION[$_REQUEST['div']]['left']= $_REQUEST['left'] ;
	}else if ($_REQUEST['monitor'] == 1) {#MySQL Monitor
		if ($_REQUEST['mode'] == 'process') {
			#show process list
			$rsl = $db->GetRow('SHOW STATUS LIKE "Threads_connected"');
			$current_connections = $rsl['Value'];
			$rsl = $db->GetRow('SHOW VARIABLES LIKE "max_connections"');
			$max_connections = $rsl['Value'];
			$sql = 'SHOW FULL PROCESSLIST';
			$rsl = $db->GetArray($sql);
			if ($rsl) {
				$r = '<h3>Process List</h3><br/>
					Current Conections: '.($current_connections-1).' / '.$max_connections;
				$r .= '<table class="debug_monitor_table">';
				$r .= '<tr><th>Id</th><th>User</th><th>Host</th><th>Db</th><th>Command</th><th>Time (sec)</th><th>State</th><th>Info</th></tr>';
				foreach ($rsl as $v) {
					if ($v['Info'] != 'SHOW FULL PROCESSLIST') $r .= '<tr><td>'.$v['Id'].'</td><td>'.$v['User'].'</td><td>'.$v['Host'].'</td><td>'.$v['db'].'</td><td>'.$v['Command'].'</td><td>'.$v['Time'].'</td><td>'.$v['State'].'</td><td>'.$v['Info'].'</td></tr>';
				}
				$r .= '</table>';
			}
		}else if ($_REQUEST['mode'] == 'query_slow' || $_REQUEST['mode'] == 'query_load' || $_REQUEST['mode'] == 'query_max') {
			#for delete query
			if ($_REQUEST['del']) {
				$sql = 'select log_md5 FROM adodb_logsql WHERE sql1=(SELECT sql1 FROM adodb_logsql WHERE log_md5="'.$_REQUEST['del'].'")';
				$log_md5 = $db->GetCol($sql);
				$sql = 'DELETE FROM adodb_logsql WHERE log_md5 IN ("'.implode('","',$log_md5).'")';
				$db->Execute($sql);
				exit;
			}
			if ($_REQUEST['mode'] == 'query_slow') {
				$header = 'Slow';
				$order_by = 'avg_execute';
			}else if ($_REQUEST['mode'] == 'query_load') {
				$header = 'Expensive';
				$order_by = 'load_time';
			}else if ($_REQUEST['mode'] == 'query_max') {
				$header = 'Max Execution Time';
				$order_by = 'max_execute';
			}
			if ($_REQUEST['max_rsl']>0) $max_rsl = $_REQUEST['max_rsl'];
			else $max_rsl = 10;
			#show query log
			$sql = 'SELECT log_md5, AVG(timer) as avg_execute, MAX(timer) AS max_execute, sql1, COUNT(1) AS sql_count, MIN(created) AS first_seen, MAX(created) AS last_seen, (AVG(timer)*COUNT(1)) AS load_time
					FROM adodb_logsql GROUP BY sql1 ORDER BY '.$order_by.' DESC LIMIT '.$max_rsl;
			$rsl = $db->GetArray($sql);
			if ($rsl) {
				$r .= '<h3>Query Analyzer: '.$header.'</h3><br/>';
				$r .= '<p><form id="query_search_rsl" action="lib/fw/debug.php?ajax=1&monitor=1&mode='.$_REQUEST['mode'].'" target="post">
						Result: <input style="text-align:right;" type="text" name="max_rsl" value="'.$max_rsl.'" size="3" maxlength="4" onKeyPress="return isNumberKey(event);">
						<input type="submit" value="submit" name="query_search_submit">
						</form></p><br/>';
				$r .= '<table class="debug_monitor_table">';
				$r .= '<tr><th colspan="3" width="170">Query Execution Time (sec)</th><th rowspan="2">First Seen</th><th rowspan="2">Last Seen</th><th rowspan="2">Count</th><th rowspan="2">Query</th><th rowspan="2"></th></tr>';
				$r .= '<tr><th>Total</th><th>Avg</th><th>Max</th></tr>';
				foreach ($rsl as $v) {
					$r .= '<tr><td>'.sprintf("%.3f", $v['load_time']).'</td><td>'.sprintf("%.3f", $v['avg_execute']).'</td><td>'.sprintf("%.3f", $v['max_execute']).'</td><td>'.$v['first_seen'].'</td><td>'.$v['last_seen'].'</td><td>'.$v['sql_count'].'</td><td><a href="#" onclick="show_debug_monitor_content(\'ajax=1&monitor=1&explain='.$v['log_md5'].'\',\'debug_log_dialog_detail\',\'SQL Explain\');" style="color:#832;">'.gain_string_cut($v['sql1']).'</a></td><td><img style="cursor:pointer;" src="im/remove.png" title="delete query" onclick="deleteQuery(\''.$v['log_md5'].'\');"></td></tr>';
				}
				$r .= '</table>';
				$r .= '<script type="text/javascript">

						function deleteQuery(log_md5){
							if (confirm("delete this query?")) {
								$.get("lib/fw/debug.php?ajax=1&monitor=1&mode='.$_REQUEST['mode'].'&del="+log_md5,function(){
									document.forms["query_search_rsl"].query_search_submit.click();
								});
							}
						}

						$(document).ready(function(){
							$("input[name=max_rsl]").focus();
							$("#query_search_rsl").ajaxForm(function(data){
								$("#debug_monitor_dialog .d_dialog_content").html(data);
							});
						});
						</script>';
			}
		}else if ($_REQUEST['mode'] == 'table') {
			#show table detail
			$sql = 'SHOW TABLE STATUS FROM '.$dbCFG['databasename'];
			$rsl = $db->GetArray($sql);
			if ($rsl) {
				$r = '<h3>Tables</h3><br/>';
				$r .= '<table class="debug_monitor_table">';
				$r .= '<tr>
						<th>Name</th>
						<th title="Dynamic datatype: varchar, text etc. (take more data free but less execution time), Fixed datatype: char, int etc. (opposite dynamic)">Row format</th>
						<th>Rows</th>
						<th title="length per a row">Avg row length</th>
						<th>Data length</th>
						<!--th>Max data length</th-->
						<th>Index length</th>
						<th title="Like Overhead, Ex. set char to 200 but most of records use just 10">Data free</th>
						<th>Auto incr</th>
						<th>Collation</th>
						</tr>';
				foreach ($rsl as $v) {
					$r .= '<tr><td>'.$v['Name'].'</td><td>'.$v['Row_format'].'</td><td class="number">'.$v['Rows'].'</td><td class="number">'.dataSize($v['Avg_row_length'],'kilo').'</td><td class="number">'.dataSize($v['Data_length'],'mega').'</td><!--td class="number">'.dataSize($v['Max_data_length']).'</td--><td class="number">'.dataSize($v['Index_length']).'</td><td class="number">'.dataSize($v['Data_free'],'byte').'</td><td class="number">'.$v['Auto_increment'].'</td><td>'.$v['Collation'].'</td></tr>';
				}
				$r .= '</table>';
			}
		}else if ($_REQUEST['explain'] != '') {
			$sql = 'SELECT sql1 FROM adodb_logsql WHERE log_md5="'.$_REQUEST['explain'].'"';
			$sql1 = $db->GetOne($sql);
			if ($sql1) {
				$sql = 'EXPLAIN '.$sql1;
				$rsl = $db->GetArray($sql);
				if ($rsl) {
					$r = '<strong>Explain</strong>: '.$sql1.'<br/><br/>';
					$r .= '<table class="debug_monitor_table">';
					$r .= '<tr><th>select_type</th><th>table</th><th>type</th><th>possible_keys</th><th>key</th><th>key_len</th><th>ref</th><th>rows</th><th>Extra</th></tr>';
					foreach ($rsl as $v) {
						$r .= '<tr><td>'.$v['select_type'].'</td><td>'.$v['table'].'</td><td>'.$v['type'].'</td><td>'.$v['possible_keys'].'</td><td>'.$v['key'].'</td><td>'.$v['key_len'].'</td><td>'.$v['ref'].'</td><td>'.$v['rows'].'</td><td>'.$v['Extra'].'</td></tr>';
					}
					$r .= '</table>';
				}
			}
			#show url which generate query
			$sql = 'SELECT DISTINCT(request_url) FROM adodb_logsql WHERE sql1=(SELECT sql1 FROM adodb_logsql WHERE log_md5="'.$_REQUEST['explain'].'")';
			$rsl = $db->GetCol($sql);
			if ($rsl) {
				#make unique url
				$request_url = array();
				foreach ($rsl as $v) {
					$request_url[] = basename($v);
				}
				$request_url = array_unique($request_url);
				$r .= '<br/><strong>URL</strong>:<br/>';
				foreach ($request_url as $v) {
					$r .= '<p><a href="'.$v.'" target="_blank">'.$v.'</a></p>';
				}
			}
		}
		$js = '<script type="text/javascript">
					var debug_url = "lib/fw/debug.php?";
					var tmp_url = "";
					function show_debug_monitor_content(url, id, title){
						if (title != "") $("div#"+id+" h3").html(title);
						$("div#"+id).show();
						if (tmp_url != url) {
							tmp_url = url;
							$("div#"+id+" div.d_dialog_content").load(debug_url+url);
						}
					}
			 </script>';
		echo $r.$js;
	}else if ($_REQUEST['debug_delete'] != '') {
		if ($_REQUEST['queries'] != '' && $_REQUEST['user'] != '' && $_REQUEST['days'] != '') {
			if ($_REQUEST['queries'] == 1 && $_REQUEST['user'] == 1 && $_REQUEST['days'] == 0) {
				$sql = 'TRUNCATE TABLE adodb_logsql';
			} else {
				$sql = 'DELETE FROM adodb_logsql WHERE';
				if ($_REQUEST['queries'] == 0) {
					$sql .= ' tracer LIKE "ERROR%" AND';
				} else if ($_REQUEST['queries'] == 2) {
					$sql .= ' tracer NOT LIKE "ERROR%" AND';
				}
				if ($_REQUEST['user'] == 0) {
					$sql .= ' debug_user="'.$_SESSION['cm_name'].'" AND';
				}
				if ($_REQUEST['days'] != 0) {
					$last_x_days = date('Y-m-d',strtotime('now - '.$_REQUEST['days'].' days'));
					$sql .= ' created < "'.$last_x_days.'" AND';
				}
				$sql = substr($sql, 0, -3);
			}
			$db->Execute($sql);
		}
	}else if ($_REQUEST['log'] != '') {
		if (!empty($_REQUEST['page'])) {
			$page_no = $_REQUEST['page'];
		} else {
			$page_no = 1;
		}
		$per_page = 30;
		$from = ($page_no - 1) * $per_page;
		$to = $from + ($per_page - 1);

		#search request
		if (isset($_REQUEST['sql_log_submit']) || isset($_REQUEST['page'])) {
			$where = array();
			if ($_REQUEST['sql_user_search']) {
				$where[] = 'debug_user="'.$_REQUEST['sql_user_search'].'"';
				$page_link_search .= '&sql_user_search='.urlencode($_REQUEST['sql_user_search']);
			}
			if ($_REQUEST['sql_url_search']) {
				$where[] = 'request_url LIKE "'.urldecode($_REQUEST['sql_url_search']).'%"';
				$page_link_search .= '&sql_url_search='.urlencode($_REQUEST['sql_url_search']);
			}
			if ($_REQUEST['sql_type_search']) {
				if ($_REQUEST['sql_type_search'] == 'errors') {
					$where[] = 'tracer LIKE "Error%"';
				} else if ($_REQUEST['sql_type_search'] == 'queries') {
					$where[] = 'tracer NOT LIKE "Error%"';
				}
				$page_link_search .= '&sql_type_search='.urlencode($_REQUEST['sql_type_search']);
			}
			if ($_REQUEST['sql_date_search']) {
				list($date_from, $date_to) = explode('to',$_REQUEST['sql_date_search']);
				$date_from = strtotime(trim($date_from));
				if (trim($date_to)) {
					$date_to = strtotime('+1 day',strtotime(trim($date_to)));
				}
				if ($date_from) {
					$where[] = 'debug_time>="'.$date_from.'"';
				}
				if ($date_to) {
					$where[] = 'debug_time<="'.$date_to.'"';
				}
				$page_link_search .= '&sql_date_search='.urlencode($_REQUEST['sql_date_search']);
			}
			if (!empty($where)) {
				$where_clause = ' WHERE '.implode(' AND ',$where);
			}
		}
		else{
			$indexstr_url = strpos($_SERVER['HTTP_REFERER'],$_SERVER['SERVER_NAME']);
			$current_url = substr($_SERVER['HTTP_REFERER'],$indexstr_url);
			$where_clause = ' WHERE debug_time>="'.strtotime(date('d M Y')).'" AND debug_user="'.$_SESSION[SESSION_N].'" AND request_url LIKE "'.$current_url.'%"';
			$page_link_search .= '&sql_user_search='.urlencode($_SESSION[SESSION_N]);
			$page_link_search .= '&sql_date_search='.urlencode(date('d M Y'));
			$page_link_search .= '&sql_url_search='.urlencode($current_url);
		}
		#get all result number
		$sql = 'SELECT COUNT(1) AS all_rows
		FROM (
			SELECT COUNT(1) FROM adodb_logsql '.$where_clause.'
			GROUP BY debug_user, debug_time, request_url
		) AS t';
		$query_length = $db->GetOne($sql);

		#get result
		$sql = 'SELECT log_md5, debug_time, debug_user, tracer, request_url
		FROM adodb_logsql
		'.$where_clause.'
		GROUP BY debug_user, debug_time, request_url
		ORDER BY debug_time DESC
		LIMIT '.$from.','.$per_page;
		$rsl = $db->GetArray($sql);

		#get query number
		$sql = 'SELECT log_md5, COUNT(1) AS u_query
		FROM adodb_logsql
		WHERE tracer NOT LIKE "Error%"
		GROUP BY debug_user,debug_time,tracer';
		$rsl_qry = $db->GetAssoc($sql);

		#get error number
		$sql = 'SELECT log_md5, COUNT(1) AS u_error
		FROM adodb_logsql
		WHERE tracer LIKE "Error%"
		GROUP BY debug_user,debug_time,tracer';
		$rsl_err = $db->GetAssoc($sql);

		$rsl_length = 0;
		$query = array();
		if ($rsl) {
			foreach ($rsl as $row) {
				$rsl_length++;
				$debug_user = explode(' ',$row['debug_user']);
				$query['date'][] = $row['debug_time'];
				$query['user_name'][] = $debug_user[0];
				$query['fullname'][] = str_replace(' ','__',$row['debug_user']);
				$query['url'][] = $row['request_url'];
				$query['query'][] = $rsl_qry[$row['log_md5']];
				$query['error'][] = $rsl_err[$row['log_md5']];
			}
		}

		#search form
		$sql = 'SELECT debug_user
		FROM adodb_logsql
		WHERE (debug_user != "" OR debug_user IS NOT NULL) GROUP BY debug_user ORDER BY debug_user';
		$debug_user = $db->GetCol($sql);
		if ($debug_user) {
			$sel_user = '<select name="sql_user_search"><option></option>';
			foreach ($debug_user as $v) {
				if ($v==$_SESSION[SESSION_N])
				$sel_user .= '<option selected="selected">'.$v.'</option>';
				else
				$sel_user .= '<option>'.$v.'</option>';
			}
			$sel_user .= '</select>';
		}

		$php_format_date = 'd M Y';
		$js_format_date = 'dd M yy';
		$sql_search_form = '<form id="sql_log_search_form" action="lib/fw/debug.php?ajax=1&log=1&page=1" method="post">
				<table>
				<tr>
					<td>User: '.$sel_user.'</td>
					<td>SQL Type: <select name="sql_type_search"><option></option><option>errors</option><option>queries</option></select></td>
					<td><input name="sql_date_search" value="'.date('d M Y').'" /></td>
					<td>Url: <input name="sql_url_search" style="width: 300px;"/></td>
					<td><input type="submit" name="sql_log_submit" value="search" /> <input type="button" value="clear" onclick="sqlClearSearchForm();" /></td>
				</tr>
				</table>
				</form>
				<script type="text/javascript">
					function sqlClearSearchForm(){
						$("#sql_log_search_form select[name=sql_user_search]").val("");
						$("#sql_log_search_form select[name=sql_type_search]").val("");
						$("#sql_log_search_form select[name=sql_url_search]").val("");
						$("#sql_log_search_form input[name=sql_date_search]").val("");
						document.forms["sql_log_search_form"].sql_log_submit.click();
					}

					$(document).ready(function(){
						$("input[name=sql_date_search]").daterangepicker({
							arrows:true,
							rangeSplitter: "to",
							dateFormat: "'.$js_format_date.'",
							onOpen: function(){
								var pos = $("input[name=sql_date_search]").offset();
								$("div.ui-daterangepickercontain").attr("style","position:absolute; top:"+(pos.top+20)+"px; left:"+(pos.left-15)+"px;");
							},
							dateStart: "'.date($php_format_date,strtotime('-3 day')).'",
							dateEnd: "'.date($php_format_date,time()).'"
						});
						$("#sql_log_search_form input[name=sql_url_search]").val("'.$_SERVER['SERVER_NAME'].'"+$("#support_app_url").text());
						$("#sql_log_search_form").ajaxForm(
							{
								target: "#sql_log_table_content",
							}
						);
					});
				</script>';

		#result table
		$r_t .= '<table width="100%" cellspacing="0" class="debug-log_table">';
		$r_t .= '<tr class="debug-row_inf1"><td colspan="6">';
		$pages = ($query_length / $per_page) + 1;
		for($i=1; $i<=$pages; $i++) {
			$page_link = '<a href="#" onclick="changePage('.$i.',\''.$page_link_search.'\')">'.$i.'</a>';
			if ($page_no == $i) $r_t .= '<b>'.$page_link.'</b> ';
			else $r_t .= $page_link.' ';
		}
		$r_t .= '</td></tr>';
		$r_t .= '<tr>
		<th style="width: 100px;">Date time</th>
		<th style="width: 150px;">User name</th>
		<th style="width: 30px;">Q</th>
		<th style="width: 30px;">E</th>
		<th>URL</th>
		</tr>';
		if ($to >= $query_length) $to = $query_length-1;
		for ($i=0; $i<=($rsl_length-1); $i++) {
			if (empty($query['error'][$i])) {
				$query['error'][$i] = 0;
			}
			$rowClass = 'debug-row_inf'.(($i%2)+1);
			if ($query['error'][$i]>0) {
				$rowClass = 'debug-row_err';
			}
			if ($query['query'][$i] > 0) {
				$query_query = $query['query'][$i];
			} else {
				$query_query = '';
			}
			if ($query['error'][$i] > 0) {
				$query_error = $query['error'][$i];
			} else {
				$query_error = '';
			}
			$r_t .= '<tr class="'.$rowClass.'"><td>'.date( "d M H:i:s" , $query['date'][$i]).'</td>';
			$r_t .= '<td valign="top">'.$query['user_name'][$i].'</td>';
			$r_t .= '<td valign="top"><a href="#" onclick="showLogDetail('.$query['date'][$i].',\''.$query['fullname'][$i].'\',0,\''.date( "d/m/Y H:i:s" , $query['date'][$i]).'\',\''.$query['url'][$i].'\');">'.$query_query.'</a></td>';
			$r_t .= '<td valign="top"><a href="#" onclick="showLogDetail('.$query['date'][$i].',\''.$query['user_name'][$i].'\',1,\''.date( "d/m/Y H:i:s" , $query['date'][$i]).'\',\''.$query['url'][$i].'\');">'.$query_error.'</a></td>';
			$r_t .= '<td valign="top"><a href="'.basename($query['url'][$i]).'" target="_blank">'.$query['url'][$i].'</a></td>';
			$r_t .= '</tr>';
		}
		$r_t .= '</table>';
		$r_t .= '<script type="text/javascript">';
		$r_t .= ' var debug_url = "lib/fw/debug.php?";
				var tmp_url = "";
				function showLogDetail(date, user, error, datetime, log_url){
					var url = debug_url+"ajax=1&E=0&debug_user="+user+"&debug_time="+date;
					show_debug_content(url,"debug_log_dialog_detail");
					//var url = debug_url+"ajax=1&logdetail=1&date="+date+"&user="+user+"&error="+error+"&log_url="+encodeURIComponent(log_url);
					//show_debug_content(url,"debug_log_dialog_detail");
					//$("div#debug_log_dialog_detail h3").html("Log detail: "+datetime+", "+user+"<br/>"+log_url);
				}
				function changePage(page,page_search_link){
					var url = debug_url+"ajax=1&log=1&page="+page+page_search_link;
					$("#sql_log_table_content").load(url);
				}';
		$r_t .= '</script>';

		#search request
		if (isset($_REQUEST['sql_log_submit']) || isset($_REQUEST['page'])) {
			$r = $r_t;
		} else {
			$r = $sql_search_form;
			$r .= '<div id="sql_log_table_content">'.$r_t.'</div>';
		}
		echo $r;
	} else if ($_REQUEST['logdetail'] != '') {
		$sql = 'SELECT log_md5, debug_time, debug_user, tracer, sql1, sql_type, created, params
		FROM adodb_logsql
		WHERE debug_user LIKE "'.$_REQUEST['user'].'%" AND debug_time='.$_REQUEST['date'].' AND request_url="'.$_REQUEST['log_url'].'"';
		if ($_REQUEST['error']) {
			$sql .= ' AND tracer LIKE "ERROR%"';
		} else {
			$sql .= ' AND tracer NOT LIKE "ERROR%"';
		}
		$sql .= ' ORDER BY created DESC';
		$rsl = $db->Execute($sql);
		$r = '<table width="100%" cellspacing="1" class="debug-log_table">';
		$r .= '<tr><th>#</th>';
		$r .= '<th>Query</th>';
		if ($_REQUEST['error']) {
			$r .= '<th>Error</th></tr>';
		} else {
			$r .= '</tr>';
		}
		$no = 0;
		while($row = $rsl->FetchRow()) {
			$no++;
			$r .= '<tr class="debug-row_inf'.(($no%2)+1).'"><td>'.$no.'</td>';
			$r .= '<td><a href="#" onclick="show_debug_log_explain(\'ajax=1&monitor=1&explain='.$row['log_md5'].'\',\'debug_temp_dialog\',\'SQL Explain\');" style="color:#111;">'.nl2br($row['sql1']).'</a></td>';
			if ($_REQUEST['error']) {
				$pos = strpos($row['tracer'], '<br>');
				$error_no_url = substr($row['tracer'], 0, $pos);
				$r .= '<td>'.$error_no_url.'</td></tr>';
			} else {
				$r .= '</tr>';
			}
		}
		$r .= '</table>';
		$js = '<script type="text/javascript">
					var debug_url = "lib/fw/debug.php?";
					var tmp_url = "";
					function show_debug_log_explain(url, id, title){
						if (title != "") $("div."+id+" h3").html(title);
						$("div."+id).show();
						if (tmp_url != url) {
							tmp_url = url;
							$("div."+id+" div.d_dialog_content").load(debug_url+url);
						}
					}
			 </script>';
		echo $r.$js;
	} else if ($_REQUEST['debug_tools'] != '') {
		$_SESSION['debug_tools'] = $_REQUEST['debug_tools'];
	} else {//Show MySQL
		$sql = 'SELECT created, timer, sql1, params, tracer, debug_user, sql_type, log_md5 FROM adodb_logsql WHERE 1 ';
		if ($_REQUEST['E']) {
			$sql .= ' AND tracer LIKE "ERROR%"';
		}

		if ($_REQUEST['sql_type'] && $_REQUEST['sql_type'] != 'other') {
			$sql .= SQL(' AND sql_type=%s',$_REQUEST['sql_type']);
		}
		if ($_REQUEST['debug_user'] != '') {
			$sql .= 'AND debug_user="'.mysql_escape_string(str_replace('__',' ',$_REQUEST['debug_user'])).'" AND debug_time="'. (int)$_REQUEST['debug_time']. '" ';
		} else if ($_REQUEST['debug_a_user'] != '') {
			$sql .= 'AND debug_user="'.mysql_escape_string(str_replace('__',' ',$_REQUEST['debug_a_user'])).'"';
		}

		$sql .= ' ORDER BY created DESC';
		$res = $db->Execute($sql);
		$colors = array(
			''=>'#666',
			'fw' => 'green',
			'app' => 'blue',
			'other' => '#666',
		);
		#
		if ($_REQUEST['E'] == 0) {
			$select_type = '<tr><td colspan="2" align="right"><select name="sql_type" onchange="filter_sql_type(this);">';
			foreach ($colors as $k => $v) {
				$select_type .= '<option value="'.$k.'">'.$k.'</option>';
			}
			$select_type .= '</select></td></tr>';
		}

		echo '<table class="debug-log_table" width="100%">
		<thead>'.$select_type.'<tr><th>#</th><th>Query</th></tr></thead><tbody>';
		$previous_create = "";
		while ($row = $res->FetchRow()) {
			$err = 0;
			if (strstr($row['tracer'], 'ERROR:')) {
				$err = 1;
			}
			if ($row['sql_type'] == '' || !$colors[$row['sql_type']]) {
				$row['sql_type'] = 'other';
			}
			$bg = $colors[$row['sql_type']];
			if ($err == 1 && $_REQUEST['E']==1) {
				if($previous_create!=date('Y-m-d',strtotime($row['created']))){
					echo '<tr class="sql_type_'.$row['sql_type'].'" style="color: #FFF; width: 100%; margin: 2px; padding: 2px 0; background: #F78A08">
							<td colspan=2 align="center"><strong>'.date('Y-m-d',strtotime($row['created'])).'
							</strong></td>
						</tr>';
					$previous_create = date('Y-m-d',strtotime($row['created']));
				}
			}
			echo '<tr class="sql_type_'.$row['sql_type'].'" style="color: #FFF; width: 100%; margin: 2px; padding: 2px 0; background:';
			if ($row['timer'] > 0.1) {
				$bg = '#DE8F07';
			}
			if ($err == 1 && !$_REQUEST['E']) {
				$bg = '#900';
			}

			$timer = $row['timer'];
			$query = nl2br(str_replace(',', ', ', htmlspecialchars($row['sql1'])));
			echo $bg.'"><td valign="top">'.(++$lk).'<br/>'.number_format($timer,3).'<br/>'.date('H:i', strtotime($row['created'])).'</td>';
			if ($err == 1) {
				echo '<td><a href="#" onclick="show_debug_log_explain(\'ajax=1&monitor=1&explain='.$row['log_md5'].'\',\'debug_temp_dialog\',\'SQL Explain\');" style="color:#FFFFFF;">'.$query.'</a>
						<br/><br/>'.stripslashes($row['tracer']).'<br/><br/>'.debug_format_print_r($row['params'],false).'</td></tr>';
			} else {
				echo '<td><a href="#" onclick="show_debug_log_explain(\'ajax=1&monitor=1&explain='.$row['log_md5'].'\',\'debug_temp_dialog\',\'SQL Explain\');" style="color:#FFFFFF;">'.$query.'</a></td></tr>';
			}
		}
		echo '</tbody></table>';
		echo '<script type="text/javascript">
					var debug_url = "lib/fw/debug.php?";
					var tmp_url = "";
					function show_debug_log_explain(url, id, title){
						if (title != "") $("div."+id+" h3").html(title);
						$("div."+id).show();
						if (tmp_url != url) {
							tmp_url = url;
							$("div."+id+" div.d_dialog_content").load(debug_url+url);
						}
					}
					function filter_sql_type(e){
						var sql_type = $(e).val();
						$("table.debug-log_table tr").show();
						if (sql_type != "") {
							$("div#debug_log_dialog_detail table.debug-log_table tbody tr[class!=sql_type_"+sql_type+"]").hide();
						}
					}

					function userQuery(e){
						//alert($(e).html());
						var url = debug_url+"ajax=1&E=1&debug_a_user="+$(e).html();
						show_debug_content(url);
					}
					$("div#debug ul.debug_menu span[id=debug_all]").click(function(){
						var url = debug_url+"ajax=1&E=1";
						show_debug_content(url);
					});
			 </script>';
	}
	exit;
}

if (!isset($_SESSION['debug_tools'])) {
	$_SESSION['debug_tools'] = 'none';
}

if (!isset($_SESSION['debug'])) {
	$_SESSION['debug']['top'] = '0px' ;
	$_SESSION['debug']['left'] = '0px' ;
}

if (!isset($_SESSION['debug_dialog'])) {
	$_SESSION['debug_dialog']['top'] = '65px' ;
	$_SESSION['debug_dialog']['left'] = '90px' ;
}

if (!isset($_SESSION['debug_log_dialog_detail'])) {
	$_SESSION['debug_log_dialog_detail']['top'] = '65px' ;
	$_SESSION['debug_log_dialog_detail']['left'] = '90px' ;
}

if (!isset($_SESSION['debug_temp_dialog'])) {
	$_SESSION['debug_temp_dialog']['top'] = '65px' ;
	$_SESSION['debug_temp_dialog']['left'] = '90px' ;
}

?>
<script type="text/javascript" src="lib/js/jquery.hotkeys.js"></script>
<link rel="stylesheet" type="text/css" href="lib/fw/debug.css" />

<div id="debug" style="color: black;">
	<div class="d_titlebar"><img class="close_button" alt="close" src="im/debug_cross.png"><h3>Debug</h3></div>
	<div class="d_dialog_content">
	<div class="debug_php_block">
		<ul class="debug_menu">
			<li><strong>PHP:</strong></li>
			<li rel="action" class="debug_php_request">R</li>
			<li rel="action" class="debug_php_files">F</li>
			<li rel="action" class="debug_php_post">P</li>
			<li rel="action" class="debug_php_session">S</li>
			<li rel="action" class="debug_php_settings">X</li>
			<?php
			global $time_start;
			$time_end = getts();
			$total = ($time_end-$time_start);
			if ($total>0.1) echo '<li title="time to load page">T: '.round($total,2).'</li>';
			?>
			<li><a target="blank" href="tools/checked_permissions.php?entity=<?php echo $_REQUEST['mod']?>">permission</a></li>
			<li><a target="blank" href="<?php echo $_SERVER['PHP_SELF']; ?>?recache=1">recache</a></li>
		</ul><ul class="debug_menu">
			<li><strong>MySQL:</strong></li>
			<li><span id="debug_query"><?php echo $db->query_count;?></span></li>
			<?php
			$sql = 'SELECT COUNT(1) count_by_user FROM adodb_logsql WHERE tracer LIKE "ERROR%"';
			$err_all = $db->GetOne($sql,'fw');
			$sql .= ' AND debug_user="'.$_SESSION[SESSION_N].'" AND debug_time="'.DEBUG_TIME.'"';
			$err_me = $db->GetOne($sql,'fw');
			$total = round($db->query_time_total,2);
			if ($total>0.1) echo '<li title="query time: all/avg">T: '.$total.'/'.round($total/$db->query_count,2).'</li>';
			?>
			<li title="error query: me/all" style="color: #A00">E:<span id="debug_one"><?php echo $err_me; ?></span>/<span id="debug_all"><?php echo $err_all; ?></span></li>
			<li><span id="debug_log"><img alt="database_log" src="im/database_table.png" title="Log list" /></span></li>
			<li><span id="debug_monitor" onclick="monitor_mode('process');"><img alt="mysql_monitor" src="im/debug_monitor.png" title="MySQL Monitor" /></span></li>
			<li><span id="debug_delete"><img src="im/remove.png" alt="delete" title="Delete" /></span></li>
		</ul>
		<ul class="debug_result debug_php">
			<li class="debug_php_request"><strong>REQUEST</strong><br/><?php echo debug_format_print_r($_REQUEST); ?></li>
			<li class="debug_php_files"><strong>FILES</strong><br/><?php echo debug_format_print_r($_FILES); ?></li>
			<li class="debug_php_post"><strong>POST</strong><br/><?php echo debug_format_print_r($_POST); ?></li>
			<li class="debug_php_session"><strong>SESSION</strong><br/><?php echo debug_format_print_r($_SESSION); ?></li>
			<li class="debug_php_settings"><strong>SETTINGS</strong><br/></li>
		</ul>
	</div>
	<div id="debug-delete_dialog">
	<label>Queries:</label>
	<select id="queries"><option value="0">Errors</option><option value="2">Query</option><option value="1" SELECTED>All</option></select>
	<label>Users:</label>
	<select id="user"><option value="0">Current</option><option value="1" SELECTED>All</option></select>
	<br/>
	Keep only last <input type="text" name="del_days" size="1" value="3"> days
	<br/><input type="submit" class="delete_button" value="Delete"/>
	</div>
</div>
</div>

<div id="debug_dialog" style="color:black;">
 	<div class="d_titlebar"><img alt="close" class="close_button" src="im/debug_cross.png"><h3>MySQL</h3></div>
 	<div class="d_dialog_content"></div>
</div>

<div id="debug_monitor_dialog" style="color:black;">
 	<div class="d_titlebar"><img alt="close" class="close_button" src="im/debug_cross.png"><h3>MySQL Monitor</h3></div>
 	<div style="padding:2px; background-color:#FFF; overflow:auto; border-left: 2px solid #848284; border-right: 2px solid #848284;">
 		<span><a onclick="monitor_mode('process');" style="color:#500;" href="#">Process List</a></span>
 		<span>| <a onclick="monitor_mode('query_slow');" style="color:#050;" href="#">Slow Query Log</a></span>
 		<span>| <a onclick="monitor_mode('query_load');" style="color:#050;" href="#">Expensive Query Log</a></span>
 		<span>| <a onclick="monitor_mode('query_max');" style="color:#050;" href="#">Max time Query Log</a></span>
		<span>| <a onclick="monitor_mode('table');" style="color:#005;" href="#">Tables</a></span>
		<span><?php echo '('.$dbCFG['hostname'].', '.$dbCFG['databasename'].')';?></span>
 	</div>
 	<div class="d_dialog_content"></div>
</div>

<div id="debug_log_dialog">
 	<div class="d_titlebar"><img alt="close" class="close_button" src="im/debug_cross.png"><h3>Log List</h3></div>
 	<div class="d_dialog_content"></div>
</div>

<div id="debug_log_dialog_detail">
 	<div class="d_titlebar"><img alt="close" class="close_button" src="im/debug_cross.png"><h3>Log detail</h3></div><!-- <h3>Log detail</h3> -->
 	<div class="d_dialog_content"></div>
</div>

<div class="debug_temp_dialog">
 	<div class="d_titlebar"><img alt="close" class="close_button" src="im/debug_cross.png"><h3>Temp dialog</h3></div>
 	<div class="d_dialog_content"></div>
</div>

<script type="text/javascript">
var debug_url = 'lib/fw/debug.php?';
var tmp_url = '';

function monitor_mode(mode){
	var url = debug_url+'ajax=1&monitor=1&mode='+mode;
	show_debug_content(url,'debug_monitor_dialog','');
}

function show_debug_content(url, id, title){
	if (id == undefined) {
		var id = 'debug_dialog';
	}
	if (title != "") $('div#'+id+" h3").html(title);
	if (tmp_url != url) {
		tmp_url = url;
		$('div#'+id+' div.d_dialog_content').load(url, function(){
			$('div#'+id).show();
		});
	}
}

$(document).ready(function(){
	var old_action = '';
	var active_block = '';
	var force_popup = 0;
	//check if we want to force to show popup
	if (($('span#debug_one').text()*1)>0) force_popup = 1;
	if ('<?php echo $_SESSION['debug_tools']; ?>' == 'block' || (force_popup == 1 && <?php echo $oCFG['force_debug_popup']?>)) {
		$('div#debug').show();
	}
	$('div#debug').css('top','<?php echo $_SESSION['debug']['top'];?>').css('left','<?php echo $_SESSION['debug']['left'];?>');
	$('div#debug_dialog').css('top','<?php echo $_SESSION['debug_dialog']['top'];?>').css('left','<?php echo $_SESSION['debug_dialog']['left'];?>');
	$('div#debug_log_dialog_detail').css('top','<?php echo $_SESSION['debug_log_dialog_detail']['top'];?>').css('left','<?php echo $_SESSION['debug_log_dialog_detail']['left'];?>');
	$('div.debug_temp_dialog').css('top','<?php echo $_SESSION['debug_temp_dialog']['top'];?>').css('left','<?php echo $_SESSION['debug_temp_dialog']['left'];?>');

	$('div#debug ul.debug_php li.debug_php_settings').append($('div#debug_settings').html());
	$('div#debug li[rel=action]').css('cursor', 'pointer').click(function(){
		var action = $(this).attr('class');
		if (action == old_action) {
			$('div#debug ul.debug_result').css('display', 'none');
			old_action = '';
		} else {
			old_action = action;
			$('div#debug ul.debug_result').css('display', 'none');
			active_block = 'div#debug ul.debug_php';
			$(active_block).css('display', 'block');
			$(active_block+' li').css('display', 'none');
			$(active_block+' li.'+action).css('display', 'block');
		}
	});

	$('div#debug ul.debug_menu span[id=debug_one]').click(function(){
//		alert("xxx");
		var url = debug_url+'ajax=1&E=1&debug_user=<?php echo str_replace(' ','__',$_SESSION[SESSION_N]);?>&debug_time=<?php echo DEBUG_TIME; ?>';
		show_debug_content(url,'debug_dialog');
	});

	$('div#debug ul.debug_menu span[id=debug_all]').click(function(){
		var url = debug_url+'ajax=1&E=1';
		show_debug_content(url,'debug_dialog');
	});

	$('div#debug ul.debug_menu span[id=debug_query]').click(function(){
		var url = debug_url+'ajax=1&E=0&debug_user=<?php echo str_replace(' ','__',$_SESSION[SESSION_N]);?>&debug_time=<?php echo DEBUG_TIME; ?>';
		show_debug_content(url,'debug_dialog');
	});

	$('div#debug ul.debug_menu span[id=debug_log]').click(function(){
		var url = debug_url+'ajax=1&log=1&url=l/tabs/index.php?mod=disbursements';//add app url
		show_debug_content(url,'debug_log_dialog');
	});

	$('div#debug,div#debug_dialog,div#debug_log_dialog_detail,.debug_temp_dialog').draggable({
		cancel: 'div.d_dialog_content,img.close_button',
		handle: "div.d_titlebar",
		stop: function(e){
			var id = $(this).attr('id');
			var top = $('div#'+id).css('top');
			var left = $('div#'+id).css('left');

			$.get(debug_url+'ajax=1&position=1&div='+id+'&top='+top+'&left='+left);
		}
	});

	$('div.d_titlebar img.close_button').click(function(){
		$.get(debug_url+'debug_tools=none&ajax=1');
		$(this).parent().parent().hide();
		//$('div#'+$(this).parent().parent().attr('id')).hide();
	});

	$('span#debug_delete').toggle(
			function (){
				$('div#debug-delete_dialog').show();
			},
			function (){
				$('div#debug-delete_dialog').hide();
			}
	);

	$('div#debug-delete_dialog input[type=submit]').click(function(){
		var queries = $('#queries').attr('value');
		var user = $('#user').attr('value');
		var days = $('div#debug-delete_dialog input[type=text]').attr('value');
		if (confirm('Delete confirmation')) {
			$.get('lib/fw/debug.php?debug_delete=1&queries='+queries+'&user='+user+'&days='+days,{ajax: "1"});
			$('div#debug-delete_dialog').hide();
		}else return false;
	});
	var debug_available = new Array('debug', 'debug_dialog', 'debug_monitor_dialog', 'debug_log_dialog', 'debug_log_dialog_detail', 'debug_temp_dialog')
	var debug_display = new Array();
	jQuery(document).bind('keydown', 'F8',function (evt){
		if ($('div#debug').css('display') == 'block') {
			for(i=0;i<debug_available.length;i++){
				if($('div#'+debug_available[i]).css('display') == 'block'){
						debug_display[i] = 1;
					}
				else	debug_display[i] = 0;
			$('div#'+debug_available[i]).css('display','none');
			}
//			$('div#debug, div#debug_dialog, div#debug_monitor_dialog, div#debug_log_dialog, div#debug_log_dialog_detail, div.debug_temp_dialog').hide();
			//check which one is open and keep in array
			//
			//hide all
			$('div#debug, div#debug_dialog, div#debug_monitor_dialog, div#debug_log_dialog, div#debug_log_dialog_detail, div.debug_temp_dialog').hide();
			//send request by $.get to update session
			$.get(debug_url+'debug_tools=none&ajax=1');
		} else {
			$('div#debug').show();
			for(i=0;i<debug_available.length;i++){
				if(debug_display[i] == 1){
						$('div#'+debug_available[i]).css('display','block');
					}
			}
			//check debug_display and show other popups
			//send request by $.get to update session
			$.get(debug_url+'debug_tools=block&ajax=1');
		}
		return false;
	});

});
</script>